package com.markerhub.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.Blog;

import com.markerhub.service.BlogService;
import com.markerhub.service.UserService;
import com.markerhub.util.ShiroUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 关注公众号：MarkerHub
 * @since 2021-05-03
 */
@Slf4j
@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    BlogService blogService;
    @GetMapping("/blogs")
    public Result lsit(@RequestParam(defaultValue = "1") Integer currentPage) {
        IPage pageData = blogService.page(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(currentPage, 5), new QueryWrapper<Blog>().orderByDesc("created"));
        log.info("查询所有的文章"+pageData.toString());
        return Result.succ(pageData);
    }
//    @RequiresAuthentication
    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {
        Blog blog = blogService.getById(id);
        Assert.notNull(blog, "该博客已删除！");
        log.info("根据id获取文章内容");
        return Result.succ(blog);
    }


    @PostMapping("/blog/edit")
    @RequiresAuthentication
    public Result edit(@Validated @RequestBody Blog blog) {

//        System.out.println(blog.toString());
        Blog temp = null;
        log.info("获取前端传递的数据"+blog.toString());
        if(blog.getId() != null) {
            log.info("用户进行发布文章,用户没有权限进行修改");
            temp = blogService.getById(blog.getId());
            Assert.isTrue(temp.getUserId() == ShiroUtil.getProfile().getId(), "没有权限编辑");
        } else {
            log.info("用户进行发布文章,用户有权限传递自己的文章");
            temp = new Blog();
            temp.setUserId(ShiroUtil.getProfile().getId());//获取当前登入的用户名字的id
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
        }
        BeanUtil.copyProperties(blog, temp, "id", "userId", "created", "status");
        blogService.saveOrUpdate(temp);
        log.info("增加文章+=============");
        return Result.succ(200,"操作成功", null);
    }



}
